package com.yzc.mihuyou.Interceptor;

import com.alibaba.fastjson.JSON;
import com.yzc.mihuyou.entity.User;
import com.yzc.mihuyou.util.TokenProccessor;
import com.yzc.mihuyou.vo.JsonResult;
import io.swagger.models.HttpMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    TokenProccessor tokenProccessor;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("token");
        System.out.println(token);
        if(token==null){
            setReturn(response,400,"异常 或 未登录");
            return false;
        }

        User puet= tokenProccessor.verify(token);
        request.getSession().setAttribute("user",puet);
        if(puet==null){
            setReturn(response,400,"token不匹配");
            return  false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
    //返回错误信息
    private static void setReturn(HttpServletResponse response, int status, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        //UTF-8编码
        httpResponse.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JsonResult jsonResult=new JsonResult(status,msg);
        String json = JSON.toJSONString(jsonResult);
        httpResponse.getWriter().print(json);

    }

}
